﻿#region "Copyright (C) Lenny Granovsky. 2005-2013"
//This program is free software distribute under the terms of the GNU General Public License as published by
//the Free Software Foundation. Please read AssemblyInfo.cs file for more information.
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Web.Enhancements.Rest.Filters
{
    /// <summary>
    /// <para>Attribute that allows to set request authorization requirement for the REST service method.</para>
    /// <para>This attribute is an optional. By default request requires authorization if attribute is set to the method. 
    /// The user names and roles are ignored if empty.</para>
    /// </summary>
    [Serializable()]
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
    public class AuthorizeAttribute : WebRestFilterAttribute
    {
        /// <summary>
        /// Gets or sets the if REST service method requires authorization.
        /// </summary>
        public bool RequiresAuthorization { get; set; }
        /// <summary>
        /// Gets or sets comma-delimited list of users allowed to use the REST service method.
        /// </summary>
        public string Users { get; set; }
        /// <summary>
        /// Gets or sets comma-delimited list of roles allowed to use the REST service method.
        /// </summary>
        public string Roles { get; set; }

        /// <summary>
        /// Default class constructor.
        /// </summary>
        public AuthorizeAttribute()
            : base()
        {
            this.RequiresAuthorization = true;
            this.Roles = "";
            this.Users = "";
        }

        /// <summary>
        /// Class constructor that accepts authorization requirement.
        /// </summary>
        /// <param name="requiresAuthorization">Boolean value indicated if authorization is required.</param>
        public AuthorizeAttribute(bool requiresAuthorization)
            : this()
        {
            this.RequiresAuthorization = requiresAuthorization;
        }

        public override System.Type FilterType
        {
            get
            {
                return typeof(AuthorizeFilter);
            }
            set
            {
                //does nothing - should not reset value. //just for interface
            }
        }

        public override IWebRestFilter CreateFilter()
        {
            char[] ch = new char[]{','};
            return new AuthorizeFilter()
            {
                RequiresAuthorization = this.RequiresAuthorization,
                Roles = new List<string>(this.Roles.Split(ch)),
                Users = new List<string>(this.Users.Split(ch))
            };
        }
    }
}
